package cn.heima.heima_netty.nio.c4;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author felix
 * @date 2024/9/11 17:31
 *
 * 1. 写入一次后若buffer不为空则监听缓冲区可写事件
 * 2. buffer剩余内容作为selectionKey附件
 * 3. 写入完成后，清除可写事件监听，清除selectionKey的附件（附件内存消耗高）
 */
public class WriteServer02 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ssc.bind(new InetSocketAddress(8099));

        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    SelectionKey sckey = sc.register(selector, SelectionKey.OP_READ);
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 5000000; i++) {
                        sb.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());
                    int write = sc.write(buffer);
                    System.out.println("写入字节:" + write);
                    if (buffer.hasRemaining()) {
                        // 在已有监听事件基础上增加缓冲区可写事件
                        sckey.interestOps(sckey.interestOps() + SelectionKey.OP_WRITE);
//                        sckey.interestOps(sckey.interestOps()|SelectionKey.OP_WRITE);
                        sckey.attach(buffer);
                    }
                } else if (key.isWritable()) {
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel sc = (SocketChannel)key.channel();
                    int write = sc.write(buffer);
                    System.out.println("写入字节:" + write);

                    if (!buffer.hasRemaining()) {
                        // 清除监听可写事件
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                        // 清除附件
                        key.attach(null);
                    }
                }
            }
        }
    }
}
